<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemUserApi } from '#/api/system/user';

import { nextTick, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { assignRemoveUserRole } from '#/api/system/permission';
import { getUserPageByRole } from '#/api/system/user';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from '../data';
import AssignUserForm from './assign-user-form.vue';

// 选择的角色
const props = defineProps({
  role: {
    type: Object as () => SystemRoleApi.Role,
    default: null,
  },
});

const [AssignUserFormModal, assignUserFormModalApi] = useVbenModal({
  connectedComponent: AssignUserForm,
  destroyOnClose: true,
});

/** 刷新表格 */
function handleRefresh() {
  gridApi.reload();
}

/** 新增用户 */
function handleCreate() {
  assignUserFormModalApi.setData({ role: props.role }).open();
}

/** 删除用角色 */
async function handleDelete(row: SystemUserApi.User) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.username]),
    duration: 0,
  });
  try {
    await assignRemoveUserRole({ userId: row.id, roleId: props.role.id });
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.username]),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: SystemUserApi.User[];
}) {
  checkedIds.value = records.map((item) => item.id!);
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    id: 'system-user-grid',
    columns: useGridColumns(),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getUserPageByRole(
            {
              pageNo: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
              roleId: props.role.id,
            },
            true,
            false,
          );
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<SystemUserApi.User>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});

// 监听 role 值变化，重新加载数据
watch(
  () => props.role,
  async (role) => {
    if (!role?.id) return;
    await nextTick();
    await gridApi.reload();
  },
  { immediate: true },
);
</script>

<template>
  <AssignUserFormModal @success="handleRefresh" />
  <Grid table-title="角色用户列表">
    <template #toolbar-tools>
      <TableAction
        :actions="[
          {
            label: $t('ui.actionTitle.create', ['用户']),
            type: 'primary',
            icon: ACTION_ICON.ADD,
            auth: ['system:user:create'],
            onClick: handleCreate,
          },
        ]"
      />
    </template>
    <template #actions="{ row }">
      <TableAction
        :actions="[
          {
            label: $t('common.delete'),
            type: 'link',
            danger: true,
            icon: ACTION_ICON.DELETE,
            auth: ['system:permission:assign-remove-user-role'],
            popConfirm: {
              title: $t('ui.actionMessage.deleteConfirm', [row.username]),
              confirm: handleDelete.bind(null, row),
            },
          },
        ]"
      />
    </template>
  </Grid>
</template>
